package com.zqweb.gulimall.ware.service.impl;

import com.zqweb.common.constant.WareConstant;
import com.zqweb.gulimall.ware.entity.PurchaseDetailEntity;
import com.zqweb.gulimall.ware.service.PurchaseDetailService;
import com.zqweb.gulimall.ware.service.WareSkuService;
import com.zqweb.gulimall.ware.vo.MergeVo;
import com.zqweb.gulimall.ware.vo.PurchaseDoneVo;
import com.zqweb.gulimall.ware.vo.PurchaseItemDoneVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zqweb.common.utils.PageUtils;
import com.zqweb.common.utils.Query;

import com.zqweb.gulimall.ware.dao.PurchaseDao;
import com.zqweb.gulimall.ware.entity.PurchaseEntity;
import com.zqweb.gulimall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.constraints.NotNull;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {
    @Autowired
    private PurchaseDetailService purchaseDetailService;
    @Autowired
    private WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils getUnReceivePurchaseForms(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
            // 分页查询出空闲状态且没有进行分配的采购单，用于封装后续产生的采购需求
                new QueryWrapper<PurchaseEntity>().eq("status",0).or()
                    .eq("status",1)
        );

        return new PageUtils(page);
    }

    @Override
    public void merge(MergeVo mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();
        List<Long> items = mergeVo.getItems();
        /**
         * 对于采购需求，可以交给多个采购人员进行采购，即使status为采购中，仍然可以合并整单
         * 只是要合并的采购单不能是已领取的（这里在展示的时候已经判断过了：0、1状态的采购单才展示
          */

        if(purchaseId == null){
            // 如果可供选择的采购单为空，则新建1个采购单，用于封装采购需求
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            purchaseEntity.setStatus(WareConstant.purchaseStatus.CREATED.getCode());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();// 重新设置新建的采购单id
        }
        // 重新获取purchaseId，否则Lambda表达式中使用原有的purchaseId变量会报错
        // Variable used in lambda expression should be final or effectively final
        Long finalPurchaseId = purchaseId;

        List<PurchaseDetailEntity> detailEntities = items.stream().map(id -> {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setId(id);
            purchaseDetailEntity.setPurchaseId(finalPurchaseId);
            purchaseDetailEntity.setStatus(WareConstant.purchaseDetailStatus.ASSIGNED.getCode());

            return purchaseDetailEntity;
        }).collect(Collectors.toList());
        purchaseDetailService.updateBatchById(detailEntities);
        // 将采购需求合并到某个空闲的可供合并的采购单后，还需要修改该采购单的updateTime
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseId);
        // 这里没必要更新新建菜单的时间，因为时间点特别邻近，只需要更新之前已存在的采购单
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);

    }

    @Override
    @Transactional
    public void receivePurchase(List<Long> ids) {// 传入的是要进行领取的采购单id数组
        List<PurchaseEntity> purchaseEntities = ids.stream().map(purchaseId -> {
            PurchaseEntity purchaseEntity = this.baseMapper.selectById(purchaseId);
            return purchaseEntity;
        }).filter(purchaseEntity -> {
            Integer status = purchaseEntity.getStatus();
            // 判断每个id对应的采购单是否是新建的或已分配的，即没有领取的，才进行领取
            if (status == WareConstant.purchaseStatus.CREATED.getCode() ||
                    status == WareConstant.purchaseStatus.ASSIGNED.getCode()) {
                return true;
            }
            return false;
        }).map(purchaseEntity -> {
            // 对需要进行领取的采购单，修改它们的状态为已领取以及updateTime
            purchaseEntity.setStatus(WareConstant.purchaseStatus.RECEIVED.getCode());
            purchaseEntity.setUpdateTime(new Date());
            return purchaseEntity;
        }).collect(Collectors.toList());
        this.updateBatchById(purchaseEntities);

        // 然后再来修改这些采购单中每个采购单中的采购需求对应的status为采购中
        purchaseEntities.forEach(purchaseEntity -> {
            Long purchaseId = purchaseEntity.getId();
            List<PurchaseDetailEntity> detailEntities = purchaseDetailService.listByPurchaseId(purchaseId);
            if(detailEntities != null && detailEntities.size() > 0){
                List<PurchaseDetailEntity> detailEntityList = detailEntities.stream().map(detail -> {
                    detail.setStatus(WareConstant.purchaseDetailStatus.BUYING.getCode());
                    return detail;
                }).collect(Collectors.toList());
                purchaseDetailService.updateBatchById(detailEntityList);
            }
        });

    }

    @Override// 采购完成的处理
    @Transactional // 开启事务处理
    public void done(PurchaseDoneVo doneVo) {
        Long purchaseId = doneVo.getId();
        // 更改采购项状态
        List<PurchaseItemDoneVo> items = doneVo.getItems();
        boolean flag = true;// 用于判断最终的采购单状态，只要采购项有1个出错，则采购单最终status为false
        List<PurchaseDetailEntity> detailEntityList = new ArrayList<>();
        for (PurchaseItemDoneVo item : items) {
            Long detailId = item.getItemId();
            Integer itemStatus = item.getStatus();
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            if(itemStatus == WareConstant.purchaseDetailStatus.HASERRORED.getCode()){
                flag = false;
                purchaseDetailEntity.setStatus(itemStatus);
            }else{
                purchaseDetailEntity.setStatus(WareConstant.purchaseDetailStatus.FINISHED.getCode());
                PurchaseDetailEntity detailEntity = purchaseDetailService.getById(detailId);
                // 将成功的商品入库
                wareSkuService.addSkuDetail(detailEntity.getSkuId(),detailEntity.getWareId(),detailEntity.getSkuNum());
            }
            purchaseDetailEntity.setId(detailId);
            detailEntityList.add(purchaseDetailEntity);
        }
        purchaseDetailService.updateBatchById(detailEntityList);

        // 更改采购单状态
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseId);
        purchaseEntity.setStatus(!flag ? WareConstant.purchaseStatus.HASERRORED.getCode() : WareConstant.purchaseStatus.FINISHED.getCode());
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);

    }

}